"""
简化的API中间件
Simplified API Middleware
"""
import logging
import time
from typing import Callable
from fastapi import Request, Response
from fastapi.responses import JSONResponse

logger = logging.getLogger(__name__)


async def error_handling_middleware(request: Request, call_next: Callable) -> Response:
    """基本错误处理中间件"""
    try:
        response = await call_next(request)
        return response
    except Exception as e:
        logger.error(f"请求处理异常: {request.method} {request.url} - {str(e)}")
        return JSONResponse(
            status_code=500,
            content={
                "error": "内部服务器错误",
                "message": "请求处理失败，请稍后重试",
                "path": str(request.url.path)
            }
        )


async def logging_middleware(request: Request, call_next: Callable) -> Response:
    """请求日志中间件"""
    start_time = time.time()
    
    # 记录请求开始
    logger.info(f"请求开始: {request.method} {request.url}")
    
    try:
        response = await call_next(request)
        
        # 计算处理时间
        process_time = time.time() - start_time
        
        # 记录请求完成
        logger.info(
            f"请求完成: {request.method} {request.url} - "
            f"状态码: {response.status_code} - "
            f"处理时间: {process_time:.3f}s"
        )
        
        # 添加处理时间到响应头
        response.headers["X-Process-Time"] = str(process_time)
        
        return response
    except Exception as e:
        process_time = time.time() - start_time
        logger.error(
            f"请求异常: {request.method} {request.url} - "
            f"错误: {str(e)} - "
            f"处理时间: {process_time:.3f}s"
        )
        raise


async def cors_middleware(request: Request, call_next: Callable) -> Response:
    """简化的CORS中间件"""
    response = await call_next(request)
    
    # 添加基本的CORS头
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
    
    return response